<template>
  <div>
    <form @keyup.enter="login">
      <div class="item">
        <input v-model.trim="username" class="input" placeholder="手机号/邮箱" type="text">
        <i class="iconfont icon-personal user" />
        <div class="box">
          <div v-show="accountState" class="error-msg">{{ hintUser }}</div>
        </div>
      </div>
      <div class="item bottom-item">
        <input v-model.trim="code" class="code-input" placeholder="请输入验证码" type="text">
        <i class="iconfont icon-key key" />
        <div class="box">
          <div v-show="codeState" class="error-msg">{{ hintCode }}</div>
        </div>
        <button class="bottom" type="button" :disabled="!canSend" @click="getCode" v-text="content">邮箱验证码</button>
      </div>
      <span>
        <div class="btn" @click="login">
          <button class="login-btn" type="button" :disabled="disabled" v-text="loginContent">登录</button>
        </div>
        <div class="function">
          <span @click="toRegister">免费注册</span>
          <span @click="toPassword">忘记密码?</span>
        </div>
      </span>
    </form>
  </div>
</template>

<script>
import { captcha } from '@/api/common'
import { countdown } from '@/util/countdown'
import { checkUserName } from '@/api/register'
import { REGEX_MOBILE_EMAIL, phoneReg } from '@/js/regex'
import { sendMobile, sendEmail, codeLogin } from '@/api/login'
export default {
  name: 'Verify',
  data() {
    return {
      content: '发送验证码', // 按钮里显示的内容
      totalTime: 60,
      canSend: true,
      clock: undefined,
      username: undefined,
      code: undefined,
      uuid: undefined,
      codeForm: {},
      disabled: false,
      loginContent: '登录',
      hintUser: '',
      hintCode: '',
      accountState: false,
      codeState: false
    }
  },
  methods: {
    async getCode() {
      if (await this.validUserName()) {
        captcha().then(response => {
          this.codeForm.uuid = response.message
          this.codeForm.code = response.data
          this.sendCode()
        })
      }
    },
    async validUserName() {
      if (!this.username) {
        this.accountState = true
        this.hintUser = '请先填写账号'
        return false
      }
      if (!REGEX_MOBILE_EMAIL.test(this.username)) {
        this.accountState = true
        this.hintUser = '账号格式不正确'
        return false
      }
      const res = await checkUserName(this.username)
      if (res.data) {
        this.accountState = true
        this.hintUser = `账号 "${this.username}" 不存在`
        return false
      }
      return true
    },
    sendCode() {
      if (!this.canSend) {
        return
      }
      countdown(this)
      const temp = phoneReg.test(this.username) ? sendMobile : sendEmail
      temp(this.codeForm, this.username).then(response => {
        if (response.data) {
          this.codeForm = {}
          this.uuid = response.message
          this.send = response.data
        }
      }).catch(res => {
        this.$message(res.data)
        this.send = false
        window.clearInterval(this.clock)
        this.content = '重新发送验证码'
        this.totalTime = 60
        this.canSend = true
      })
    },
    async login() {
      if (await this.validUserName()) {
        if (!this.send) {
          this.accountState = false
          this.codeState = true
          this.hintCode = '请先获取验证码'
          return
        }
        if (!this.code) {
          this.accountState = false
          this.codeState = true
          this.hintCode = '请先填写验证码'
          return
        }
        this.disabled = true
        this.loginContent = '登录中...'
        codeLogin(this.username, this.code, this.uuid).then(response => {
          this.$store.dispatch('setToken', response.data)
          const spuRepoId = this.$route.params.spuRepoId
          if (spuRepoId) {
            location.reload()
            return
          }
          let redirect = this.$route.query.redirect
          if (redirect) {
            const index = redirect.split('redirect')
            redirect = index.length > 0 ? index[index.length - 1].replace('=', '') : redirect
            this.$router.push({
              path: decodeURIComponent(redirect)
            })
          } else {
            this.$router.push('/')
          }
        }).catch(() => {
          this.disabled = false
          this.loginContent = '登录'
        })
      }
    },
    toRegister() {
      this.$emit('registered')
    },
    toPassword() {
      this.$emit('password')
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  text-align: center;
  .iconfont {
    position: absolute;
  }
  .item {
    position: relative;
    .user {
      font-size: 24px;
      top: 26px;
      left: 35px;
    }
    .box{
      height: 28px;
      .error-msg{
        text-align: left;
        padding-left: 20px;
        color: #f56c6c;
      }
    }
    .pass {
      font-size: 22px;
      top: 26px;
      left: 36px;
    }
    .key {
      font-size: 20px;
      top: 6px;
      left: 36px;
    }
    .input {
      width: 317px;
      height: 42px;
      border: 1px solid #e5e5e5;
      margin-top: 20px;
      text-indent: 44px;
    }
    .code-input{
      width: 317px;
      height: 42px;
      border: 1px solid #e5e5e5;
      text-indent: 44px;
    }
    .btn-input {
      width: 92px;
      height: 42px;
      background: #f1f1f1;
      color: #8e8e93;
    }
  }
  .bottom-item {
    position: relative;
    .bottom {
      width: 92px;
      height: 42px;
      background: #f1f1f1;
      color: #8e8e93;
      text-align: center;
      line-height: 42px;
      font-size: 14px;
      position: absolute;
      top: 0;
      right: 20px;
      cursor: pointer;
    }
  }
  .function {
    display: flex;
    justify-content: space-between;
    margin: 10px 20px 0 20px;
    span {
      cursor: pointer;
    }
  }
  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 317px;
    height: 42px;
    background: #ff3b30;
    border-radius: 6px;
    margin: 0 0 0 20px;
    cursor: pointer;
    .login-btn {
      cursor: pointer;
      font-size: 20px;
      color: #ffffff;
      &:disabled{
        background: #00000073;
      }
    }
  }
}
</style>
